package org.balabala.gateway.response;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.TypeReference;
import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回数据
 *
 * @author Mark sunlightcs@gmail.com
 */
public class Resp extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;
    //自定义设置数据方法
    public Resp setData(Object data){
        put("data",data);
        return  this;
    }

    /**
     * @param key 获取指定key的名字
     */
    public <T> T getData(String key, TypeReference<T> typeReference){
        // get("data") 默认是map类型 所以再由map转成string再转json
        Object data = get(key);
        return JSON.parseObject(JSON.toJSONString(data), typeReference);
    }
    //typeReference是一个数据类型
    //类型逆转方法
    public <T> T getData(TypeReference<T> typeReference){
        Object data = get("data");
        //先将对象转化为字符串
        String s = JSON.toJSONString(data);
        //将字符转化为输入的数据类型
        T t = JSON.parseObject(s,typeReference);
        return  t;
    }

    public Resp() {
        put("code", 0);
        put("msg", "success");
    }

//    public static Resp error() {
//        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
//    }

    public static Resp error(String msg) {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    }

    public static Resp error(int code, String msg) {
        Resp resp = new Resp();
        resp.put("code", code);
        resp.put("msg", msg);
        return resp;
    }

    public static Resp ok(String msg) {
        Resp resp = new Resp();
        resp.put("msg", msg);
        return resp;
    }

    public static Resp ok(Map<String, Object> map) {
        Resp resp = new Resp();
        resp.putAll(map);
        return resp;
    }

    public static Resp ok() {
        return new Resp();
    }

    public Resp put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public int getCode() {
        return (Integer)this.get("code");
    }
}
